package IOdemo;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class FileWriter_0618 {
    private static final String url = "jdbc:mysql://localhost:3306/xk?EncodingCharacter = UTF8&useSSL=false";
    private static final String user = "root";
    private static final String password = "123456";

    public static void main(String[] args) throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl(url);
        ((MysqlDataSource) dataSource).setUser(user);
        ((MysqlDataSource) dataSource).setPassword(password);
        Connection connection = dataSource.getConnection();
        String sql = "select * from student";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        try(OutputStream outputStream = new FileOutputStream("test.txt")) {
            PrintWriter printWriter = new PrintWriter(outputStream);
            printWriter.printf("%s\t%s\t%s\t%s\t%s", "学号", "姓名", "年龄", "性别", "年级");
            printWriter.println();
            while (resultSet.next()) {
                printWriter.printf("%d\t%s\t%d\t%s\t%s", resultSet.getInt("id"),
                        resultSet.getString("name"),
                        resultSet.getInt("age"),
                        resultSet.getString("gender"),
                        resultSet.getString("grade"));
                printWriter.println();
                printWriter.flush();
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            resultSet.close();
            preparedStatement.close();
            connection.close();
        }
    }
}
